package com.example.gokuplayalong.bases.push;

import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.bases.mysql.MysqlDruid;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.example.gokuplayalong.bases.base.ExceptionHandler;

@Controller
public class PublishController {


    @RequestMapping("/pushMessageToOne")
    @ResponseBody
    public void pushMessageToOne(@RequestParam("phone") String phone, @RequestParam("extras") String extras) {

        try {

            List<String> rids = new ArrayList<>();
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            Connection conn = MysqlDruid.dataSource.getConnection();

            pstmt = conn.prepareStatement("select * from ridslist where phone=\"" + phone + "\"");
            rs = pstmt.executeQuery();
            while (rs.next() && !StringUtils.isEmpty(rs.getString("rid"))) {
                rids.add("\"" + rs.getString("rid") + "\"");
            }
            conn.close();

            Push.createPushByRids("你收到了一条新消息,点击查看", rids, JSONObject.parseArray(extras));
        } catch (Throwable e) {
            ExceptionHandler.saveException(Thread.currentThread().getStackTrace()[1].getMethodName(), e);
        }

    }

    @RequestMapping("/pushMessageToAll")
    @ResponseBody
    public void pushMessageToAll() {
        try {
            List<String> rids = new ArrayList<>();
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            Connection conn = MysqlDruid.dataSource.getConnection();

            pstmt = conn.prepareStatement("select * from ridslist");
            rs = pstmt.executeQuery();
            while (rs.next() && !StringUtils.isEmpty(rs.getString("rid"))) {
                rids.add("\"" + rs.getString("rid") + "\"");
            }
            conn.close();
            JSONObject extras = new JSONObject();
            extras.put("key", "type");
            extras.put("value", "聊天消息");
            Push.createPushByRids("你收到了一条新消息,点击查看", rids, extras);
        } catch (Throwable e) {
            ExceptionHandler.saveException(Thread.currentThread().getStackTrace()[1].getMethodName(), e);
        }

    }


}
